#include "imageloadthread.h"
#include <QStack>
#include <QDir>
#include <QDebug>
#include <QThread>

ImageLoadThread::ImageLoadThread(QObject *parent) : QObject(parent)
{
    _loadTimer = nullptr;
}

ImageLoadThread::~ImageLoadThread()
{
}

void ImageLoadThread::startWork(float interval,const QString& folderPath)
{

    if(_last_path != folderPath){

        _last_path = folderPath;
        scanImageFromFolderPath(folderPath);
        // 启动定时器
        _current_index = 0;
    }

    _loadTimer->start(interval * 1000);
}

void ImageLoadThread::stopWork()
{
    _loadTimer->stop();
}

void ImageLoadThread::setTimerInterval(float interVal)
{
    if(_loadTimer->isActive()){
        _loadTimer->stop();
    }

    _loadTimer->start(interVal * 1000);
}

void ImageLoadThread::slot_timeOutLoadImage()
{
    if(_Image_Path_Vec.isEmpty()){
        return;
    }

    if(_current_index >= _Image_Path_Vec.size()){
        _current_index = 0;
    }

    // 加载图片
    QImage image;
    image.load(_Image_Path_Vec[_current_index++]);

    emit sig_loadImage(image);
}

void ImageLoadThread::scanImageFromFolderPath(const QString &folderPath)
{
    // 通过文件夹路径查询图片名称
    QStack<QString> g_folderPath;
    g_folderPath.push(folderPath);

    QStringList g_imageSuffixList({"jpg","jpeg","png","bmp","gif"});

    _Image_Path_Vec.clear();

    while(!g_folderPath.isEmpty()){
        QString fPath = g_folderPath.pop();

        QDir dir(fPath);
        if(!dir.exists()){ // 不存在
            continue;
        }
        QFileInfoList infoList = dir.entryInfoList(QDir::Files
                           | QDir::Dirs | QDir::NoDotAndDotDot);
        for(const auto& info : infoList){
            if(info.isDir()){
                g_folderPath.push(info.filePath());
            }else{
                // 获取后缀名称
                QString suffix = info.suffix();
                if(g_imageSuffixList.contains(suffix,Qt::CaseInsensitive)){
                    _Image_Path_Vec.push_back(info.filePath());
                }
            }
        }
    }
}

void ImageLoadThread::initTimer()
{
    if(!_loadTimer){
        _loadTimer = new QTimer(this);
        connect(_loadTimer,&QTimer::timeout,this,&ImageLoadThread::slot_timeOutLoadImage);
    }
}

